package com.jp.juc.completableFuture;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

public class M4 {


    public static void main(String[] args) throws ExecutionException, InterruptedException {


        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

        try {
            List<Long> taskList = startTask(executorService);
        } finally {
            executorService.shutdown();
        }
    }

    private static List<Long> startTask(ExecutorService executorService) throws InterruptedException, ExecutionException {
        List<Long> dataIds = new CopyOnWriteArrayList<>();

        // 任务
        CompletableFuture<List<Long>> future1 = CompletableFuture.supplyAsync(() -> {
            List<Long> list = queryData1();
            dataIds.addAll(list);
            return list;
        }, executorService);

        CompletableFuture<List<Long>> future2 = CompletableFuture.supplyAsync(() -> {
            List<Long> list = queryData2();
            dataIds.addAll(list);
            return list;
        }, executorService);

        CompletableFuture<List<Long>> future3 = CompletableFuture.supplyAsync(() -> {
            List<Long> list = queryData3();
            dataIds.addAll(list);
            return list;
        }, executorService);


        AtomicBoolean flag = new AtomicBoolean(true);


        CompletableFuture<Void> completableFuture = CompletableFuture.allOf(future1, future2, future3)
                .whenCompleteAsync((v, e) -> {
                    if (e == null) {
                        System.out.println("操作成功");
                    }
                })
                .exceptionally((e) -> {
                    System.out.println("异常信息：" + e.getMessage());
                    e.printStackTrace();
                    flag.set(false);
                    return null;
                });

        completableFuture.get();

        if (!flag.get()) {
            throw new RuntimeException("==任务执行失败==");
        }

        System.out.println("--task--" + dataIds);

        return dataIds;
    }


    public static List<Long> queryData1() {
        System.out.println("==queryData1==" + Thread.currentThread().getName());
        return new ArrayList<Long>() {
            {
                add(1L);
            }
        };
    }

    public static List<Long> queryData2() {
        System.out.println("==queryData2==" + Thread.currentThread().getName());
        return new ArrayList<Long>() {
            {
                add(2L);
            }
        };
    }

    public static List<Long> queryData3() {
        System.out.println("==queryData3==" + Thread.currentThread().getName());
        ArrayList<Long> arrayList = new ArrayList<Long>() {
            {
                add(3L);
            }
        };
        //int i = 1 / 0;
        return arrayList;
    }

}
